﻿namespace Reap.AzureResource.Web.Controllers {
	using System;
	using System.Data;
	using System.Data.SqlClient;
	using System.Linq;
	using System.Threading.Tasks;
	using System.Web.Mvc;

	using Newtonsoft.Json;
	using Newtonsoft.Json.Converters;

	using Reap.AzureResource.Model.Models;
	using Reap.AzureResource.Service;

	public class HomeController:AsyncController {
		private ILocationService locationService;

		private IResourceService resourceService;
		public HomeController(ILocationService locationService,IResourceService resourceService) {
			this.locationService = locationService;
			this.resourceService = resourceService;
		}

		#region Public Methods and Operators

		public async Task<ContentResult> GetListTask() {

			//SELECT *,DATEDIFF(ss,r.UploadEndTime,r.UploadEndTime) AS intervalTimeFROM Location AS l,Resource AS r WHERE l.Id=r.LocationId AND r.LocationId IS NOT NULL
			using(
				SqlConnection conn =
					new SqlConnection(
						"Data Source=10.1.0.103;Initial Catalog=AzureResource;Persist Security Info=True;User ID=sa;Password=dahua123;MultipleActiveResultSets=True")
				) {
				conn.Open();
				using(SqlCommand cmd = new SqlCommand()) {
					cmd.Connection = conn;
					cmd.CommandText = "SELECT *,isnull(furl,'10.1.1.46') AS furls,r.Fstatus as FResourcestatus,r.Id AS resourceId,DATEDIFF(ss,r.UploadStartTime,r.UploadEndTime) AS intervalTime FROM Location AS l,Resource AS r WHERE l.Id=r.LocationId AND r.LocationId IS NOT NULL order by r.id desc";
					cmd.CommandType = CommandType.Text;
					using(SqlDataAdapter adapter = new SqlDataAdapter()) {
						adapter.SelectCommand = cmd;
						DataSet ds = new DataSet();
						adapter.Fill(ds,Guid.NewGuid().ToString());

						DataTable dt = ds.Tables[0];
						var timeConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy'-'MM'-'dd' 'HH':'mm':'ss" };
						var jsonData = JsonConvert.SerializeObject(dt,timeConverter);
						return await Task.Run(() => Content(jsonData));
					}

				}

			}

		}

		public async Task<ActionResult> Index() {
			return await Task.Run(() => this.View());
		}

		public async Task<ActionResult> EdiTask() {
			return await Task.Run(() => this.View());
		}

		public async Task<ActionResult> SaveTask(Location location,int? resourceId) {

			return await Task.Run(
				() => {
					location.CreateTime = DateTime.Now;
					location.Fstatus = !string.IsNullOrEmpty(Request.Form["Fstatus"]);
					locationService.AddLocation(location);
					var resource = resourceService.GetResourceById(resourceId ?? 0);
					if(resource == null) {
						return this.RedirectToAction("index");
					}
					resource.LocationId = location.Id;
					this.resourceService.UpdateResource(resource);
					return RedirectToAction("index");
				});

		}
		#endregion
	}
}